package com.situ.mall.controller.front;

import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.PageObjectUtil;
import com.mysql.fabric.xmlrpc.base.Data;
import com.situ.mall.common.ServerResponse;
import com.situ.mall.constant.MallConstant;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.Order;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.entity.Product;
import com.situ.mall.entity.Shipping;
import com.situ.mall.entity.User;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IOrderItemService;
import com.situ.mall.service.IOrderService;
import com.situ.mall.service.IProductService;
import com.situ.mall.service.IShippingService;
import com.situ.mall.util.CartUtil;
import com.situ.mall.vo.CartItemVO;
import com.situ.mall.vo.CartVO;

@Controller
@RequestMapping(value="/order")
public class FrontOrderController {
	@Autowired
	private IShippingService shippingService;
	@Autowired
	private IProductService productService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IOrderItemService orderItemService;
	@Autowired
	private ICartService cartService;
	
	
	@RequestMapping(value="/getOrderPage.shtml")
	public String getOrderPage(Integer userId,Model model,HttpServletRequest request,HttpSession session) {
		//根据userId查出收获地址
		List<Shipping> shippings = shippingService.selectByUserId(userId); 
		model.addAttribute("shippings",shippings);
		System.out.println(shippings);
		
		/*纯cookie---------------------------------------------------*/
		/*CartVO cartVO = CartUtil.getCartVOFromCookie(request);
		if(cartVO != null){
			List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
			//迭代器
			Iterator<CartItemVO> iterator = cartItemVOList.iterator();
			//判断有没有下一个
			while (iterator.hasNext()) {
				CartItemVO item = iterator.next();
				//把没有勾选的移除,isChecked==0的
				if (item.getIsChecked() == MallConstant.CART_UNCHECKED) {
					iterator.remove();
					continue;
				}
				
				// CartItemVO里面的Product只有id，我们要在购物车页面展示商品的详细信息，
				// 所以要根据这个id查找出产品的详细信息，直接把原来的Product替换
				Product product = productService.selectByPrimaryKey(item.getProduct().getId());
				item.setProduct(product);
			}
			model.addAttribute("cartVO",cartVO);
		}*/
		/*纯cookie-----------------------------------------------------*/
	
		//数据库
		User user = (User) session.getAttribute("user");
		
		List<Cart> carts = cartService.selectByUserId(user.getId());
		List<CartItemVO> cartItemVOList = new ArrayList<>();
		for (Cart cart : carts) {
			if (cart.getChecked() == 1) {
				Product product = productService.selectByPrimaryKey(cart.getProductId());
				CartItemVO cartItemVO = new CartItemVO();
				cartItemVO.setProduct(product);
				cartItemVO.setAmount(cart.getQuantity());
				cartItemVO.setIsChecked(cart.getChecked());
				cartItemVOList.add(cartItemVO);
			}
		}
		CartVO cartVO = new CartVO();
		cartVO.setCartItemVOList(cartItemVOList);
		model.addAttribute("cartVO",cartVO);
		return "order/place_order";
	}
	
	//添加订单的order表和order_item表-----------------------------------------------------
	@RequestMapping(value="/addOrder.shtml")
	@ResponseBody
	public ServerResponse addOrder(HttpSession session,Integer shippingId,BigDecimal payment,HttpServletRequest request,HttpServletResponse response) {
		//插入order表--------Start
		//拿到user对象
		User user = (User) session.getAttribute("user");
		
		//创建订单对象
		Order order = new Order();
		//生成时间的订单号
		Date date = new Date();
		SimpleDateFormat toOrderNo = new SimpleDateFormat("yyyyMMddhhmmss");
		String orderNo = toOrderNo.format(date);
		Long orderNoLong = Long.parseLong(orderNo);//把订单号转换为long类型
		
		order.setOrderNo(orderNoLong);//订单号
		order.setUserId(user.getId());//user表id
		order.setShippingId(shippingId);//收货表id
		order.setPayment(payment);//实际付款金额
		order.setPaymentType(1);//支付方式，在线支付
		order.setPostage(0);//运费0元
		order.setStatus(20);//已付款
		System.out.println(order);
		//插入order表格
		orderService.addOrder(order);
		//插入order表--------End
		
		/*cookie方式---------------------------------------*/
		/*//插入 order_item表   cookie方式------Start
		CartVO cartVO = CartUtil.getCartVOFromCookie(request);
		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		Iterator<CartItemVO> iterator = cartItemVOList.iterator();
		while (iterator.hasNext()) {
			CartItemVO cartItemVO = iterator.next();
			if (cartItemVO.getIsChecked() == MallConstant.CART_CHECKED) {
				// 将CartItemVO转换成OrderItem
				OrderItem orderItem = new OrderItem();
				orderItem.setUserId(user.getId());//用户ID
				orderItem.setOrderNo(order.getOrderNo());//直接拿到上面的订单号
				orderItem.setProductId(cartItemVO.getProduct().getId());//productId
				//product里面只有一个id所以要更新，查出来数据
				Product product = productService.selectByPrimaryKey(cartItemVO.getProduct().getId());
				orderItem.setProductName(product.getName());//productName
				orderItem.setProductImage(product.getMainImage());//图片
				orderItem.setCurrentUnitPrice(product.getPrice());//单价
				orderItem.setQuantity(cartItemVO.getAmount());//数量
				//求出每件商品的总价格，因为单价product.getPrice()是decimal类型，需要转换类型在相乘
				BigDecimal  toPrice  = new BigDecimal(cartItemVO.getAmount().toString());//转换为decimal类型
				BigDecimal totalPrice  = product.getPrice().multiply(toPrice);//相乘
				orderItem.setTotalPrice(totalPrice);
				System.out.println(orderItem);
				//数据插入数据库
				orderItemService.addOrderItem(orderItem);
				//cookie已经插入订单数据库，所以要移除cookie
				iterator.remove();
			}
		}
		//插入 order_item表------End
		//将购物车写回cookie
		CartUtil.setCartVOToCookie(cartVO, response);*/
		/*cookie方式-------------------------------------*/
		
		/*数据库方式添加*/
		List<Cart> carts = cartService.selectByUserId(user.getId());
		for (Cart cart : carts) {
			if (cart.getChecked() == 1) {
				OrderItem orderItem = new OrderItem();
				orderItem.setUserId(user.getId());//userID
				orderItem.setOrderNo(order.getOrderNo());//订单号
				orderItem.setProductId(cart.getProductId());
				Product product = productService.selectByPrimaryKey(cart.getProductId());
				orderItem.setProductName(product.getName());//商品名
				orderItem.setProductImage(product.getMainImage());//商品图品
				orderItem.setCurrentUnitPrice(product.getPrice());//单价
				orderItem.setQuantity(cart.getQuantity());//数量
				//求出每件商品的总价格，因为单价product.getPrice()是decimal类型，需要转换类型在相乘
				BigDecimal  toPrice  = new BigDecimal(cart.getQuantity().toString());//转换为decimal类型
				BigDecimal totalPrice  = product.getPrice().multiply(toPrice);//相乘
				orderItem.setTotalPrice(totalPrice);
				//数据插入数据库
				orderItemService.addOrderItem(orderItem);
			}
		}
		//插入成功后删除Cart表
		cartService.deleteByUserId(user.getId());
		
		return ServerResponse.createSuccess("成功");
	}
	
	
	//确认后的订单页面
	@RequestMapping(value="/getUserOrderPage.shtml")
	public String getUserOrderPage(HttpSession session,Model model) {
		User user = (User)session.getAttribute("user");
		List<Order> orders = orderService.selectOrder(user.getId());
		List<OrderItem> orderItems = orderItemService.selectOrderItem(user.getId());
		
		model.addAttribute("orders",orders);
		model.addAttribute("orderItems",orderItems); 
		return "order/user_order";
	}
}
